package socket;

import com.sun.xml.internal.ws.resources.SenderMessages;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/**聊天室服务端*/
public class Server {
    /*运行在服务端的ServerSocket,主要作用两个:
        1:开启服务端口,客户端就是通过这个端口与服务端建立连接的.(ServerSocket构造方法)
        2:监听该端口,一旦一个客户端连接时,就会返回一个Socket实例与其通讯.(accept()方法的作用)*/
    private ServerSocket serverSocket;
    //保存所有客户端的输出流用于广播消息
//    private PrintWriter[] allOut = {};
    private Collection<PrintWriter> allOut = new ArrayList<>();
    public Server(){
        try {
            System.out.println("正在启动服务端");
            /*可能报错:java.net.BindException:address already in use  端口被占用*/
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**程序开始*/
    public void start(){
        try{
            while (true){
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();//阻塞方法  程序会卡在这里
                System.out.println("一个客户端连接了");
//                createThread(socket);//方法创建线程
                //启动一个负责处理该客户端交互
                ClientHandler r1 = new ClientHandler(socket);
                Thread t1 = new Thread(r1);
                t1.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    /**创建线程
     * 该线程任务负责与指定客户端进行交互*/
    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录当前客户端IP地址
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                //通过刚接受连接的socket,获取输入流来读取该客户端发送过来的消息
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                //通过socket获取输出流;
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                //将该输出流存入到共享数组allOut中
                /*this,所属对象究竟是谁?run方法调用this,ClientHandler的实例对象调用run
                 *锁临界资源
                 * 数组为null,扩容容易空指针
                 * 锁一个扩容数组,锁不住(更换数组对象)*/
//            synchronized (this) {//不同线程调用不同的ClientHandler的run方法,因此run方法中的this(ClientHandler不是同一个)
//            synchronized (allOut) {//线程进入到同步块中会创建新的数组对象赋值给allOut,导致其如果作为锁对象会发生改变.
                synchronized (allOut) {
                    allOut.add(pw);
                    //1.将allOut扩容
//                    allOut = Arrays.copyOf(allOut, allOut.length + 1);
                    //2.将当前pw存入数组最后一个位置
//                    allOut[allOut.length - 1] = pw;
                }
            sendMessage(host+"上线了,当前在线人数为:"+allOut.size());

            String line;
            /*使用readLine()读取远端计算机发送过来消息时,对应断开操作不同,这里体现的结果不同,
            * 可能存在如下情况:
            * 1.当远端计算机调用socket.close(),此时对方会进行正常的TCP四次挥手断开连接,那么readLine方法会返回null
            * 2:readLine()方法抛出异常:java.net.SocketException: connection reset
                      说明客户端是非正常退出的(没有进行TCP挥手操作)*/
            while ((line = br.readLine()) != null){
                //创建sendMessage()来发送信息给各客户端
                sendMessage(host+"说:"+line);
            }
            } catch (IOException e) {
//                e.printStackTrace();
                sendMessage(host+"非正常下线");
            }finally {
                //处理与客户端断开的操作
                //将pw从数组中删除
                synchronized (allOut){
                    allOut.remove(pw);
                /*for (int i = 0; i < allOut.length; i++) {
                    if (pw == allOut[i]){
                        allOut[i] = allOut[allOut.length - 1];
                        allOut = Arrays.copyOf(allOut,allOut.length -1);
                        break;//结束循环,提高性能
                    }
                }*/
                }
                sendMessage(host+"下线了,当前在线人数为:"+allOut.size());
                try {
                    /*输入输出同时关闭*/
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessage(String message){
            System.out.println(message);
            //将消息发送给所有客户端
            synchronized (allOut){//控制不同线程同时发消息
                /*for (int i = 0; i < allOut.length; i++) {
                    allOut[i].println(message);
                }*/
                for (PrintWriter sendMessage : allOut) {
                    sendMessage.println(message);
                }
            }
        }
    }
    public void createThread(Socket socket){
        Thread thread = new Thread(() -> {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null){
                    System.out.println(line);
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}
